import { Module } from "vuex";

import localCache from "@/utils/localCache";

import { IRootState } from "../type";
import { ILoginState } from "./type";
import { IUserInfoType } from "@/service/login/type";
import {
  numberLoginRequset,
  requestUserInfoById,
  requestUserMenuByRoleId
} from "@/service/login/login";
import router from "@/router";
import { mapMunuToRoutes, mapMenuToPermission } from "@/utils/mapMenu";

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenu: [],
      permission: []
    };
  },
  mutations: {
    changeUserToken(state, token: string) {
      state.token = token;
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changeUserMenu(state, userMenu: any) {
      state.userMenu = userMenu;
      // 拿到当前角色所能看到菜单的路由对象
      const routes = mapMunuToRoutes(userMenu);
      // 动态添加路由
      for (const route of routes) {
        router.addRoute("main", route);
      }
      // 获取当前用户的权限字符串
      const permission = mapMenuToPermission(userMenu);
      state.permission = permission;
    }
  },
  getters: {},
  actions: {
    async numberLoginAction({ commit }, payload: IUserInfoType) {
      // 用户登录
      const userAuth = await numberLoginRequset(payload);
      commit("changeUserToken", userAuth.data.token);
      localCache.setCache("token", userAuth.data.token);

      // 查询用户基本信息
      const userInfo = await requestUserInfoById(userAuth.data.id);
      commit("changeUserInfo", userInfo.data);
      localCache.setCache("userInfo", userInfo.data);

      // 获取角色菜单
      const userMenu = await requestUserMenuByRoleId(userInfo.data.role.id);
      commit("changeUserMenu", userMenu.data);
      localCache.setCache("userMenu", userMenu.data);

      // 跳转路由
      router.push("/");
    },
    reloadLoginData({ commit }) {
      const token = localCache.getCache("token");
      if (token) {
        commit("changeUserToken", token);
      }
      const userInfo = localCache.getCache("userInfo");
      if (userInfo) {
        commit("changeUserInfo", userInfo);
      }
      const userMenu = localCache.getCache("userMenu");
      if (userMenu) {
        commit("changeUserMenu", userMenu);
      }
    }
  }
};
export default loginModule;
